<template>
  <div class="business">
    <div class="title">加班申请</div>
        <!-- <el-button type="success">成功按钮</el-button> -->


    <div class="opes">
      <el-button type="success" @click="drawer = true">发起新的</el-button>
      <!-- headers 设置上传请求头 -->
      <!-- data 上传请求需要携带的参数 -->
      <!-- action 上传地址 -->
      <!-- name 上传字段, 字段值必须是 excel -->

      <!-- on-success 文件上传成功时的回调 -->
      <el-upload
        :show-file-list="false"
        :on-success="onSuccess"
        class="upload"
        :headers="headers"
        :data="{userid:userinfo._id}"
        name="excel"
        action="/api/work/import">
        <el-button type="warning" round>导入</el-button>
      </el-upload>
      
      <el-button type="warning" round> 
        <el-link :href="'/api/work/download?userid='+userinfo._id">导出</el-link> 
      </el-button>
    </div>


    <el-tabs v-model="activeName" >
      <el-tab-pane label="待办事项" name="1">
        <!-- 渲染表格组件 -->
      <MyTable 
      :columns="columns"
      :total="total"
      :businesslist="businesslist"
      :handleCurrentChange="handleCurrentChange"
      :deleteRow="deleteRow"
      > 
      </MyTable>

    </el-tab-pane>
      <el-tab-pane label="已办事项" name="2">已办事项</el-tab-pane>
      <el-tab-pane label="抄送事项" name="3">抄送事项</el-tab-pane>
      <el-tab-pane label="我发起的" name="4">我发起的</el-tab-pane>
      <el-tab-pane label="全部数据" name="5">全部数据</el-tab-pane>
      <el-tab-pane label="概览" name="6">概览</el-tab-pane>
      <el-tab-pane label="统计爆表" name="7">
        <!-- 绘制图表的位置 -->
        <MyEchart></MyEchart>
      </el-tab-pane>
    </el-tabs>

      
      

   
    <!-- 抽屉 -->
    <el-drawer
      :visible.sync="drawer">
      <el-form 
        :model="ruleForm" 
        status-icon 
        :rules="rules" 
        ref="ruleForm" 
        label-width="100px" 
        class="business-box">
        <h3 class="title">加班申请</h3>
        <el-form-item label="申请人" prop="name">
          <el-input type="text" v-model="ruleForm.name" autocomplete="off" placeholder="申请人"></el-input>
        </el-form-item>

        <el-form-item label="加班类型" prop="type">
          <el-select v-model="ruleForm.type" placeholder="请选择加班类型">
            <el-option value="0"></el-option>
            <el-option value="1"></el-option>
            <el-option value="2"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="事由说明" prop="reason">
          <el-input type="textarea" v-model="ruleForm.reason" autocomplete="off" placeholder="请输入内容"></el-input>
        </el-form-item>

        <el-form-item label="开始时间" prop="starttime">
          <el-date-picker
            v-model="ruleForm.starttime"
            type="datetime"
            placeholder="选择开始时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="结束时间" prop="endtime">
          <el-date-picker
              v-model="ruleForm.endtime"
              type="datetime"
              placeholder="选择结束时间">
            </el-date-picker>
        </el-form-item>


        <el-form-item label="加班时长" prop="hours">
          <el-input type="text" v-model="ruleForm.hours" autocomplete="off" placeholder="加班总时长（小时）"></el-input>
        </el-form-item>


        <el-form-item class="footer">
          <el-button type="primary" @click="submitForm()">提交</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

  </div>
</template>

<script>
import { mapState } from 'vuex'
import { work_add,work_list,work_delete} from '../../utils/api'
import MyTable from '../../components/MyTable.vue'
import MyEchart from '../../components/MyEchart.vue'


export default {
  data(){
   var validateName = (rule, value, callback) => {
        if ( value.length<2 ) {
          callback(new Error('请输入正确的申请人'));
        } else {
          callback();
        }
      };
   var validateType = (rule, value, callback) => {
        if ( !value ) {
          callback(new Error('请选择正确的加班类型'));
        } else {
          callback();
        }
      };
   var validateReason = (rule, value, callback) => {
        if ( !value ) {
          callback(new Error('请输入正确的申请人'));
        } else {
          callback();
        }
      };
   var validateStarttime = (rule, value, callback) => {
        if ( !value ) {
          callback(new Error('请选择加班开始时间'));
        } else {
          callback();
        }
      };
   var validateEndtime = (rule, value, callback) => {
        if ( !value || (new Date(this.ruleForm.starttime) - new Date(value)) > 0) {
          callback(new Error('请选择结束时间'));
        } else {
           //计算加班总时长                                                                   除以一小时的毫秒
          this.ruleForm.hours =  ( new Date(value) - new Date(this.ruleForm.starttime) ) / (60*60*1000)
          callback();
        }
      };
   var validateHours = (rule, value, callback) => {
        if ( Number(value) < 0.5) {
          callback(new Error('请输入正确的加班时长'));
        } else {
          callback();
        }
      };

    return {
      headers:{Authorization:'Bearer ' + localStorage.getItem('token')},
      drawer:false,//控制抽屉组件是否显示
      total:0,//出差申请总数
      page:1,//页码
      businesslist:[],
      ruleForm:{
        type:'',
        reason:'',
        name: this.$store.state.userinfo.name,
        starttime:'',
        endtime:'',
        hours:0,
      },
      rules: {
       name: [
            //validator 验证器  trigger 触发器
            { validator: validateName, trigger: 'blur' }
          ],
          type: [
            //validator 验证器  trigger 触发器
            { validator: validateType, trigger: 'blur' }
          ],
         reason: [
          { validator: validateReason, trigger: 'blur' }
          ],
          starttime: [
            { validator: validateStarttime, trigger: 'blur' }
          ],
          endtime: [
          { validator: validateEndtime, trigger: 'blur' }
          ],
         hours: [
          { validator: validateHours, trigger: 'blur' }
          ],
         
      },
      activeName:'1',
     columns:[
          {
            prop:"_id",
            label:'编号'
          },
          {
            prop:"status",
            label:'当前流程状态',
            formatter:this.formater_status
          },
          {
            prop:"name",
            label:'申请人'
          },
          {
            prop:"type",
            label:'加班类型',
            formatter:this.formater_type
          },
          {
            prop:"reason",
            label:'加班事由'
          },
          {
            prop:"starttime",
            label:'开始时间',
            formatter:this.formater_time

          },
          {
            prop:"endtime",
            label:'结束时间',
            formatter:this.formater_time
          },
          {
            prop:"hours",
            label:'加班总时长'
          },
        ]
    }
  },
  components:{
    MyTable,
    MyEchart
  },

  mounted(){
    work_list({ userid: this.userinfo._id ,page:1 }).then((res)=>{
      this.businesslist = res.data.list;
      this.total = res.data.total;
    })
   
  },
  computed:{
    ...mapState(['userinfo'])
  },
  methods:{
    submitForm(){
      this.$refs.ruleForm.validate((valid)=>{
        if( valid ){
          work_add( {userid: this.userinfo._id ,...this.ruleForm }).then((res)=>{
            // console.log(res.data)
            if( res.data.code == 200 ){
              this.$message.success(res.data.msg);
              this.drawer = false;//隐藏抽屉
            }else{
              this.$message.error(res.data.msg);
            }
          })

        }else{
          console.log('验证失败');

        }
      })
    },

    handleCurrentChange(val){
      this.page = val; //保存页码
      //请求对应页码的数据
      work_list({ userid: this.userinfo._id ,page:val }).then((res)=>{
        this.businesslist = res.data.list;
      })
    },
    deleteRow(id){
      //删除对应id的 出差申请
      work_delete({userid: this.userinfo._id , id ,page: this.page }).then((res)=>{
        this.businesslist = res.data.list;
        this.total = res.data.total;
        this.$message.success(res.data.msg);
      })
    },
    onSuccess(res){
      if( res.code == 200 ){
        this.$message.success(res.msg);
      }else{
        this.$message.error(res.msg);
      }
    },
    formater_status(row, column, cellValue, index){
      console.log(cellValue)
          return cellValue == 0 ? '待审批' : '已通过';
      },
      formater_type(row, column, cellValue, index){
       if( cellValue==0){
        return '工作日加班'
       }
       if( cellValue==1){
        return '周末加班'
       }
       if( cellValue==2){
        return '节假日加班'
       }
    },

      formater_num(num){
          return num < 10 ? '0'+num : num;
      },

      formater_time(row, column, cellValue, index){
          var d = new Date( cellValue );
          return `${d.getFullYear()}-${ this.formater_num( d.getMonth()+1 ) }-${ this.formater_num( d.getDate() ) }` ;
      },  
  }
}
</script>

<style lang='scss'>
.business{
  .title{
    margin: 10px 0;
    width: 100%;
    border-bottom: 1px solid #ccc;
  }
  .opes{
  margin: 20px 0;
  display: flex;
  .upload{
    margin: 0 20px;
  }
}
}
.business-box{
  padding: 20px;
  .title{
    margin-bottom: 20px;
  }
}
.pagination{
  margin-top: 20px;
}
#main{
  width: 500px;
  height: 300px;
}
</style>